﻿using AutoMapper;
using MediatR;
using ZGLXM.ErrorCode;
using ZGLXM.Infra.Interface;
using ZGLXM.Infra.Repository;
using ZGLXM.Writh.Api.Applicantion.Command.RBAC;

namespace ZGLXM.Writh.Api.Applicantion.Handler.RBAC
{
    public class ProfessionUpdateCommandHandler : IRequestHandler<ProfessionUpdateCommand, ApiResult>
    {
        private readonly IProfessionRepository professionRepository;
        private readonly IMapper mapper;

        public ProfessionUpdateCommandHandler(IProfessionRepository professionRepository, IMapper mapper)
        {
            this.professionRepository = professionRepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult> Handle(ProfessionUpdateCommand request, CancellationToken cancellationToken)
        {
            var profession = await professionRepository.GetAsync(x => x.ProfessionId == request.ProfessionId && x.IsDeleted == false);
            if (profession == null)
            {
                return ApiResult.Fail("信息不存在");
            }
            var entity = mapper.Map(request, profession);
            var res = await professionRepository.UpdateAsync(entity);
            if (res > 0)
            {
                return ApiResult.OK("权限更新成功");
            }
            return ApiResult.Fail("权限更新失败");
        }
    }
}
